﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Topic : System.Web.UI.Page
{

    #region VARIABLES

    Service service;
    OneTopic theTopic;
    Validation validation;

    #endregion 


    #region PROPERTIES

    private UserCredentials User
    {
        get { return Session["user"] as UserCredentials; }
        set { Session["user"] = value; }
    }

    #endregion 


    protected void Page_Load(object sender, EventArgs e)
    {
        validation = new Validation();
        int topicID = 0;
        if (Request.QueryString["topic"] != null)
        {
            try
            {
                topicID = Convert.ToInt32(Request.QueryString["topic"]);
            }
            catch (Exception error)
            {
                TopicDoesNotExist();
            }
        }
        if (topicID > 0)
        {
            noTopicH2.Visible = false;
            service = new Service();
            theTopic = service.GetTopicOnID(Convert.ToInt32(Request.QueryString["topic"]));
            if (theTopic != null)
            {
                if (theTopic.Deleted != "true")
                {
                    if (!IsPostBack)
                    {

                        HeaderTextBox.Text = theTopic.Header;
                        TopicText.Text = theTopic.TextContent;
                        AuthorLabel.Text = theTopic.Author;
                        DateLabel.Text = theTopic.Date;
                    }
                    EditButton.PostBackUrl = String.Format("~/Topic.aspx?topic={0}&edit=true", theTopic.TopicID);

                    if (theTopic.UserID == User.UserID)
                    {
                        EditButton.Visible = true;
                        DeleteButton.Visible = true;
                    }
                    else
                    {
                        EditButton.Visible = false;
                        DeleteButton.Visible = false;
                    }

                    if (Request.QueryString["edit"] == "true")
                    {
                        if (validation.IfUserWithIDWroteTopicWithID(User.UserID, theTopic.TopicID) || User.UserRole.ToString() == "Admin")
                        {
                            CommentsDiv.Visible = false;
                            HeaderTextBox.Enabled = true;
                            TopicText.Enabled = true;
                            EditButton.Visible = false;
                            DeleteButton.Visible = false;
                            CompleteEditButton.Visible = true;
                        }
                        else
                        {
                            OnlyTheAuthorCan();
                            Response.Redirect(String.Format("~/Topic.aspx?topic={0}", Request.QueryString["topic"]));
                        }
                    }

                    if (topicID > 0 && Request.QueryString["delete"] != null && Request.QueryString["delete"].ToString() == "true")
                    {
                        if (validation.IfUserWithIDWroteTopicWithID(User.UserID, topicID) ||
                            User.UserRole.ToString() == "Admin")
                        {
                            service.DeleteTopicOnID(Convert.ToInt32(Request.QueryString["topic"]));
                            Response.Redirect("~/Forum.aspx");
                        }
                        else
                        {
                            OnlyTheAuthorCan();
                        }
                    }
                }
                else
                {
                    // Topicen är deleted
                    TopicDoesNotExist();
                }
            }
            else
            {
                //Topicen finns inte.
                TopicDoesNotExist();
            }
        }
        else
        {
            //Topic id är mindre än 1 av någon anledning..kan ju inte kolla om null så.
            TopicDoesNotExist();
        }
        
    }


    private void OnlyTheAuthorCan()
    {
        string message = ("Only the author can Delete/Edit this topic");
        Session["errorMessage"] = message;
    }

    private void TopicDoesNotExist()
    {
        string message = ("The topic you tried to view does not exist.");
        Session["errorMessage"] = message;
        Response.Redirect("~/Forum.aspx");
    }

    public bool DeleteButtonVisible(int topicUserID)
    {
        if (topicUserID == User.UserID || User.UserRole.ToString() == "Admin")
        {
            return true;
        }
        return false;
    }




    #region BUTTON_ONCLICK METHODS


    protected void CommentButton_Click(object sender, EventArgs e)
    {       
        if (validation.ValidateCommentContentLength(CommentTextbox.Text))
        {
            Sanitize sanitize = new Sanitize();
            Comment comment = new Comment();

            string textContent = sanitize.EncodeText(CommentTextbox.Text);

            comment.TextContent = textContent;
            comment.TopicID = Convert.ToInt32(Request.QueryString["topic"]);
            comment.UserID = User.UserID;

            service.SaveComment(comment);

            Response.Redirect(String.Format("~/Topic.aspx?topic={0}", Request.QueryString["topic"]));
        }
        else
        {
            DisplayAllErrorMessages();
        }
    }



    protected void CompleteEditButton_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["edit"] == "true" &&
            validation.IfUserWithIDWroteTopicWithID(User.UserID, theTopic.TopicID) || User.UserRole.ToString() == "Admin")
        {
            string sanitizedHeader = validation.SanitizeText(HeaderTextBox.Text);
            string sanitizedContent = validation.SanitizeText(TopicText.Text);

            if (validation.ValidateNewTopic(sanitizedHeader, sanitizedContent))
            {
                OneTopic topic = new OneTopic();

                topic.Header = sanitizedHeader;
                topic.TextContent = sanitizedContent;
                topic.TopicID = theTopic.TopicID;

                service.SaveTopic(topic);
                AddSessionSuccesMessage("The Topic Has Been Updated");
                Response.Redirect("~/Forum.aspx");
            }
            else
            {
                List<string> errormessages = validation.GetErrorMessages();

                if (errormessages != null)
                {
                    foreach (string error in errormessages)
                    {
                        AddErrorMessage(error);
                    }
                }
            }
        }
        else
        {
            Response.Redirect(String.Format("~/Topic.aspx?topic={0}",Request.QueryString["topic"]));
        }
    }

 
    protected void DeleteButton_Click(object sender, EventArgs e)
    { 
        Response.Redirect(String.Format("~/Topic.aspx?topic={0}&delete=true", Request.QueryString["topic"].ToString()));
    }


    #endregion 



    protected void ObjectDataSource1_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
    {
     
    }


    private void DisplayAllErrorMessages()
    {
        List<string> errormessages = validation.GetErrorMessages();

        if (errormessages != null)
        {
            foreach (string error in errormessages)
            {
                AddErrorMessage(error);
            }
        }
    }


    #region  AddErrorMessage

    private void AddErrorMessage(string message)
    {
        Validators.Add(new CustomValidator
        {
            ErrorMessage = message,
            IsValid = false
        });
    }

    private void AddErrorMessage(IDataErrorInfo obj)
    {
        obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .Where(n => !String.IsNullOrWhiteSpace(obj[n])) // vill bara ha de som inte är tomma.
            .ToList()  // gör om till lista.
            .ForEach(n => AddErrorMessage(obj[n]));  // loopar igenom namnen som återstår o lägger till.
    }

    #endregion


    public void AddSessionSuccesMessage(string message)
    {
        Session["successMessage"] = message;
    }

    protected void ListView1_ItemDeleted(object sender, ListViewDeletedEventArgs e)
    {
        if (e.Exception == null)
        {
            string successMessage = ("The comment has been deleted.");
            Session["successMessage"] = successMessage;
            Response.Redirect(String.Format("~/Topic.aspx?topic={0}", Request.QueryString["topic"]));
        }
        else
        {
            string message = ("An Error Has Occured When Trying To Delete The Comment");
            Session["errorMessage"] = message;
            Response.Redirect(String.Format("~/Topic.aspx?topic={0}", Request.QueryString["topic"]));
        }
    }
}